package com.clm.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clm.waimai.common.BaseContext;
import com.clm.waimai.common.R;
import com.clm.waimai.dto.OrderDto;
import com.clm.waimai.entity.*;
import com.clm.waimai.service.AddressBookService;
import com.clm.waimai.service.OrderDetailService;
import com.clm.waimai.service.OrderService;
import com.clm.waimai.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    @CacheEvict(value = "shoppingCart", key = "#orders.userId + '_' + 'shoppingCart'")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 后台获取用户订单信息
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){
        //构造分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number != null, Orders::getNumber, number);
        queryWrapper.between(beginTime !=null, Orders::getOrderTime, beginTime, endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //执行分页查询
        orderService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> list = records.stream().map((item) ->{
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(item, orderDto);

            //提取地址id
            Long addressBookId = item.getAddressBookId();
            //从地址表中查询用户名
            AddressBook addressBook = addressBookService.getById(addressBookId);
            String userName = addressBook.getConsignee();

            orderDto.setUserName(userName);

            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);

        return R.success(orderDtoPage);
    }

    /**
     * 根据id修改订单信息
     * @param order
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders order){
        log.info("修改订单信息：{}", order);
        orderService.updateById(order);
        return R.success("修改订单信息成功");
    }

    /**
     * 用户订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){
        Long userId = BaseContext.getCurrentId();
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != userId, Orders::getUserId, userId);
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //进行分页查询
        orderService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> list = records.stream().map((item) ->{
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(item, orderDto);

            //查询当前订单的订单细节，从order_detail表中获取
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDto.setOrderDetails(orderDetails);
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);

        return R.success(orderDtoPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        //获得当前用户的id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        //购物车有东西
            if(!shoppingCarts.isEmpty()){
            shoppingCartService.remove(wrapper);
        }
        //购物车没东西
        //查询订单细节集合
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
        //将订单里的菜品添加到购物车中
        //创建购物车集合
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        shoppingCartList = orderDetails.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //对象拷贝
            BeanUtils.copyProperties(item, shoppingCart, "id", "orderId");
            //设置购物车用户
            shoppingCart.setUserId(userId);
            //设置创建日期，都是订单细节里没有的
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //保存购物车
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("再来一单成功");
    }
}
